import { FormEvent } from "react";

import { ResponseProps } from "type/http";
import { useAuth } from "content/auth-content";
import { useAsync } from "utils/hooks/use-async";

export const LoginPage = ({ onError }: { onError: (error: Error | null) => void }) => {
  const { login } = useAuth();
  const { run, isLoading, isError, error } = useAsync<any>(undefined, { throwOnError: true });

  const handSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const username = (e.currentTarget.elements[0] as HTMLInputElement).value;
    const password = (e.currentTarget.elements[1] as HTMLInputElement).value;
    try {
      await run(login({ username, password }));
    } catch (e) {
      onError((e as Error));
    }
  }

  return (
    <div className="login-container">
      <form action="#" onSubmit={handSubmit}>
        <div>
          <label htmlFor="">用户名</label>
          <input type="text" id="username" />
        </div>
        <div>
          <label htmlFor="">密码</label>
          <input type="password" id="password" />
        </div>
        <button type="submit" disabled={isLoading}>登录</button>
      </form>
    </div>
  );
}